const ajax = require("ajax");
const xhrutils = require("xhrutils");
const utils = require("utils");
const common = require('common');
cc.Class({
    extends: cc.Component,

    properties: {

        progress: cc.Node
    },

    // use this for initialization
    onLoad: function() {
        cc.log('this.progress.progress:' + this.progress.progress);
        this.progress.getComponent(cc.ProgressBar).progress = 0.5;
        this.progress.active = false;
    },
    setBookName: function(bookname) {
        this.node.getChildByName('bookname').getComponent(cc.Label).string = bookname;
    },
    setBookFace: function(url) {
        let self = this;
        cc.loader.load(url, function(err, sf) {
            cc.log('load remote bookface' + err + sf);
            self.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(sf);
        });
        // xhrutils.loadNativeImg(url,function(textrue,i){
        //     cc.log('this is '+textrue);
        //     self.getComponent(cc.Sprite).spriteFrame=new cc.SpriteFrame(textrue);
        //  },0);
        //this.getComponent(cc.Sprite).spriteFrame.setTexture
    },
    setBtn: function(json, isdownload) {
        let self = this;
        let readbtn = self.node.getChildByName('readbtn');
        let downloadbtn = self.node.getChildByName('downloadbtn');
        let progress = this.progress;
        readbtn.bookid = json.id;
        downloadbtn.bookid = json.id;

        if (!isdownload)
            self.node.getChildByName('already').active = false;
        //直接阅读，将远程的bookjson合并到本地后，打开，离线时没打开的页是打不开的
        readbtn.on(cc.Node.EventType.TOUCH_END, function() {
            cc.log('uuid:' + this.uuid + ' bookid:' + this.bookid);
            let bookjsonurl = "http://odxmd36pu.bkt.clouddn.com/" + this.bookid + ".json";
            if (json.json) {
                bookjsonurl = json.json;
            }
            ajax.getJSON(bookjsonurl, function(thisbookjson) {
                //var common = cc.find('common');

                //往里放之前要看一眼的
                let flag = true;
                for (var i = 0; i < common.init.bookdata.length - 1; i++) {
                    if (common.init.bookdata[i].id == json.id) {
                        flag = false;
                    }
                }
                if (flag) {
                    common.init.bookdata.push(thisbookjson);
                }


                if (!isdownload) {


                    jsb.fileUtils.writeStringToFile(JSON.stringify(common.init.bookdata), jsb.fileUtils.getWritablePath() + "bookdata.json");
                }
                common.init.current_bookid = thisbookjson.id;
                common.init.current_page = 1;
                cc.director.loadScene("book");
            });
            // cc.loader.load(jsb.fileUtils.getWritablePath()+'bookdata.json',function(err,txt){
            //     cc.log('txt:'+txt);
            // });
            //再从远程下载这本书自己的bookjson，然后合并到bookdata.js中
        });
        //下载阅读，将远程的bookjson合并到本地，下载每一页缓存到本地，这样就可以离线了
        downloadbtn.on(cc.Node.EventType.TOUCH_END, function() {
            let thisbtn = this;
            let bookjsonurl = "http://odxmd36pu.bkt.clouddn.com/" + this.bookid + ".json";
            if (json.json) {
                bookjsonurl = json.json;
            }
            //var common = cc.find('common');
            //let toast = common.init.setMessage('正在下载中。。。');
            progress.active = true;
            cc.log('progress' + progress.getComponent(cc.ProgressBar).progress);
            progress.getComponent(cc.ProgressBar).progress = 0;
            // utils.getToast().fadein(1);
            // cc.log('utils.getToast():' + utils.getToast());
            cc.log('bookjsonurl:'+bookjsonurl);
            ajax.getJSON(bookjsonurl, function(thisbookjson) {
                
                cc.eventManager.pauseTarget(thisbtn, true);

                //下载所有资源，还是要对一下是否有？
                let resourcesurl = [];
                //图片资源
                for (var i = 0; i < thisbookjson.pages.length; i++) {
                    let picurl = thisbookjson.perfix + thisbookjson.path + "/" + thisbookjson.pages[i].pic + '.' + (thisbookjson.pages[i].pictype ? thisbookjson.pages[i].pictype : 'jpg');
                    let clipurl = thisbookjson.perfix + thisbookjson.path + "/" + thisbookjson.pages[i].clip + '.mp3';
                    let explainurl = thisbookjson.perfix + thisbookjson.path + "/" + thisbookjson.pages[i].explain + '.mp3';
                    resourcesurl.push(picurl);
                    if (thisbookjson.pages[i].clip) {
                        resourcesurl.push(clipurl);
                    }
                    if (thisbookjson.pages[i].explain) {
                        resourcesurl.push(explainurl);
                    }
                }
                //可能由于七牛的限制，太快了之后会下不下来，再来一次就好了
                //但这时需要关闭显示。
                xhrutils.loadAll(resourcesurl, function(rs) {
                    cc.log('load before: ' + common.init.bookdata.length + ' json.id:' + json.id + isdownload);
                    if (!isdownload) {
                        //这里其实要后写，在下载完成后再往JSON中写。
                        //往里放之前要看一眼的
                        let flag = true;
                        for (var i = 0; i < common.init.bookdata.length; i++) {
                            // cc.log('?????????'+common.bookdata[i].id+'='+json.id);
                            if (common.init.bookdata[i].id == json.id) {
                                flag = false;
                            }
                        }
                        if (flag) {
                            common.init.bookdata.push(thisbookjson);
                        }

                        jsb.fileUtils.writeStringToFile(JSON.stringify(common.init.bookdata), jsb.fileUtils.getWritablePath() + "bookdata.json");
                    }
                    //common.current_index = common.bookdata.length - 1;
                    common.init.current_page = 1;

                    cc.eventManager.resumeTarget(thisbtn, true);
                    //要刷新书架

                    common.init.toast('下载完成', function() {
                        cc.log('download complete ' + thisbookjson.bname);
                        progress.runAction(cc.fadeOut(1));
                        cc.find('Canvas').getComponent('bookshelf').bookshelfcontent.getComponent('bookshelfcontent').init(common.init.bookdata);
                    });
                    //将原来的已下载刷新
                    self.node.getChildByName('already').active = true;
                }, function(ratio) {
                    progress.getComponent(cc.ProgressBar).progress = ratio;
                }, function(index) {
                    common.init.toast('下载未完成，请重新下载', function() {
                        cc.eventManager.resumeTarget(thisbtn, true);
                    });
                });
            });
        });
    },
    setDownLoad: function() {
        let self = this;
        self.node.getChildByName('already').active = false;
    },


});